﻿using System;
using System.IO;
using System.Media;
using System.Threading;
using System.Windows.Forms;
using KuaiPanSDK;
using KuaiPanSDK.Model;
using SkinSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Web;

namespace DemoSDKForWinForm
{
    public partial class DemoSDK : Form
    {
        /// <summary>
        /// 是否选中了文件夹
        /// </summary>
        private bool isSelectedDirectory = false;

        /// <summary>
        /// 是否选中了文件
        /// </summary>
        private bool isSelectedFile = false;

        /// <summary>
        /// 是否已经复制了一份记录
        /// </summary>
        private bool isCopyFiled = false;

        /// <summary>
        /// 是否已经复制了一份记录
        /// </summary>
        private bool isCutFiled = false;

        /// <summary>
        /// 是不是新建文件夹
        /// </summary>
        private bool isAddDirectory = false;

        /// <summary>
        ///  修改文件夹
        /// </summary>
        private bool isModeDirectory = false;

        private Tag CopyTag;

        private delegate void BeginInvokeDelegate();
        public KuaiPan SDK { get; private set; }
        private Icons sysIcons = new Icons();
        public SkinH_Net skinh;
        public DemoSDK()
        {
            skinh = new SkinH_Net();
            skinh.Attach();
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.listView.SmallImageList = sysIcons.ImageList;
            this.treeView.ImageList = sysIcons.ImageList;

            this.listView.Columns.Add("columnsName", "名称", 200);
            this.listView.Columns.Add("columnsSize", "大小", 80);
            this.listView.Columns.Add("columnsType", "类型", 120);
            this.listView.Columns.Add("columnsMax", "修改日期", 120);
            bool isneed = true;
            //556a38e8908d480b89f7a3904b36b62e|0a2a7b443ffb4e4ab7b1575829128cd6
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "config.txt"))
            {
                StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "config.txt", System.Text.Encoding.UTF8);
                string str = sr.ReadToEnd();
                if (str.IndexOf("|") > 10)
                {
                    string[] s = str.Split('|');
                    this.SDK = new KuaiPan(s[0], s[1]);
                    isneed = false;
                }
                sr.Close();
            }

            if (isneed)
            {
                this.SDK = new KuaiPan();
                string url = this.SDK.GetAuthorizationUrl();

                Process proc = Process.Start("iexplore.exe", url);
                if (proc != null)
                {
                    MessageBox.Show("授权完请关闭浏览器", "授权提示");
                    proc.WaitForExit();
                }
                if (!this.SDK.GetAccessToken())
                {
                    MessageBox.Show("授权完请关闭浏览器", "授权失败");
                    Application.Exit();
                }
                StreamWriter sw = new System.IO.StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "config.txt", false, new System.Text.UTF8Encoding(false));
                sw.Write(this.SDK.Token + "|" + this.SDK.TokenSecret);
                sw.Close();
            }


            Thread a = new Thread(delegate()
            {
                this.SetAccountInfo();
                this.BeginInvoke(new BeginInvokeDelegate(delegate()
                {
                    this.LoadTree();
                }));
            });
            a.Start();
        }

        private void SetAccountInfo()
        {
            AccountInfo info = this.SDK.GetAccountInfo();
            if (info != null)
            {
                this.BeginInvoke(new BeginInvokeDelegate(delegate()
                        {
                            this.lbl_UserName.Text = info.UserName;
                            this.lbl_MaxFileSize.Text = Common.CountSize(info.MaxFileSize);
                            this.lbl_QuotaTotal.Text = Common.CountSize(info.QuotaTotal);
                            this.lbl_QuotaUsed.Text = Common.CountSize(info.QuotaUsed);
                        }));
            }
            else
            {
                MessageBox.Show(this.SDK.ErrMsg, "错误");
            }
        }

        private void LoadPath(string path, TreeNode pathnode, bool isLoad)
        {
            this.listView.Items.Clear();  //移除所的项目和列
            this.listView.AllowColumnReorder = true;
            MetaData metadata = this.SDK.GetMetaData(path, null);
            if (metadata != null)
            {
                string pathtemp = string.Empty;
                foreach (FileData file in metadata.Files)
                {
                    pathtemp = (metadata.Path + "/" + file.Name).Replace("//", "/");
                    if (file.Type == TypeEnum.Folder && !pathnode.Nodes.ContainsKey("Folder_" + file.Name))
                    {
                        TreeNode node = pathnode.Nodes.Add("Folder_" + file.Name, file.Name, 1, 2);
                        node.Tag = new Tag(pathtemp);
                        if (isLoad)
                        {
                            this.LoadPath(pathtemp + "/", node, false);
                        }
                    }
                    if (!isLoad)
                    {
                        continue;
                    }
                    ListViewItem item = new ListViewItem();
                    item.Text = file.Name;
                    item.Tag = new Tag(pathtemp, file.Name);

                    if (file.Type == TypeEnum.Folder)
                    {
                        item.SubItems.Add("");
                        item.ImageIndex = 1;
                    }
                    else
                    {
                        item.SubItems.Add(Common.CountSize(file.Size));
                        item.ImageIndex = sysIcons.GetIconIndex(file.Name, false);
                    }
                    item.SubItems.Add(Icons.GetExtsDescription(file.Name));
                    item.SubItems.Add(file.ModifyTime.ToString());

                    this.listView.Items.Add(item);
                }
                if (isLoad)
                {
                    this.lbl_Path.Text = path;
                }
            }
        }

        private void LoadTree()
        {
            this.treeView.Nodes.Clear();
            TreeNode rootnode = this.treeView.Nodes.Add("root", "根目录");
            rootnode.Tag = new Tag(string.Empty);
            rootnode.ImageIndex = 1;
            rootnode.SelectedImageIndex = 2;
            this.treeView.SelectedNode = rootnode;
            rootnode.Expand();
        }

        //在选中某个节点的时候发生的事情,这边都是对文件夹进行操作
        private void treeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            Tag tag = (Tag)e.Node.Tag;
            if (tag != null)
            {
                this.LoadPath(tag.Path + "/", e.Node, true);
            }
            this.isSelectedFile = false;
            this.isSelectedDirectory = false;
            this.EnableControlMenu();
        }

        //鼠标双击ListView控件时发生的事件
        private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.listView.SelectedItems.Count != 1 || this.isAddDirectory || this.isModeDirectory)
            {
                return;
            }
            //通过大小判断
            string size = this.listView.SelectedItems[0].SubItems[1].Text;
            string file = this.listView.SelectedItems[0].SubItems[0].Text;
            if (string.IsNullOrEmpty(size.Trim()))
            {
                this.listView.Items.Clear();  //移除所的项目和列
                TreeNode node = this.treeView.SelectedNode.Nodes.Find("Folder_" + file, true)[0];
                this.treeView.SelectedNode = node;
                this.treeView.SelectedNode.Expand();
            }
        }

        private void listView_SelectedIndexChanged(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1);
            if (isSelecte)
            {
                string size = this.listView.SelectedItems[0].SubItems[1].Text;
                if (string.IsNullOrEmpty(size.Trim()))
                {
                    this.isSelectedDirectory = true;
                    this.isSelectedFile = false;
                }
                else
                {
                    this.isSelectedDirectory = false;
                    this.isSelectedFile = true;
                }
            }
            else
            {
                this.isSelectedFile = false;
                this.isSelectedDirectory = false;
            }
            this.EnableControlMenu();
        }

        private void EnableControlMenu()
        {
            this.tlsm_ListView_Copy.Enabled = (this.listView.SelectedItems.Count == 1) && (this.isSelectedDirectory || this.isSelectedFile);
            this.tlsm_ListView_Cut.Enabled = (this.listView.SelectedItems.Count == 1) && (this.isSelectedDirectory || this.isSelectedFile);
            this.tlsm_ListView_Paste.Enabled = !(this.isSelectedDirectory || this.isSelectedFile) && (this.isCopyFiled || this.isCutFiled);
            this.tlsm_ListView_Delete.Enabled = (this.listView.SelectedItems.Count == 1) && (this.isSelectedDirectory || this.isSelectedFile);
            this.tlsm_ListView_ReName.Enabled = (this.listView.SelectedItems.Count == 1) && (this.isSelectedDirectory || this.isSelectedFile);
            this.tlsm_ListView_NewFolder.Enabled = !(this.isSelectedDirectory || this.isSelectedFile);
            this.tlsm_ListView_Down.Enabled = (this.listView.SelectedItems.Count == 1) && (this.isSelectedFile);
            this.tlsm_ListView_Shares.Enabled = (this.listView.SelectedItems.Count == 1) && (this.isSelectedFile);
        }

        #region ListView右键删除
        private void tlsm_ListView_Delete_Click(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1 && !this.isAddDirectory && !this.isModeDirectory);
            if (isSelecte)
            {
                string size = this.listView.SelectedItems[0].SubItems[1].Text;
                string file = this.listView.SelectedItems[0].SubItems[0].Text;
                DialogResult result = MessageBox.Show("确定要删除此" + (string.IsNullOrEmpty(size) ? "文件夹" : "文件") + "吗", "删除提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if (result == DialogResult.OK)
                {
                    Tag tag = ((Tag)this.listView.SelectedItems[0].Tag);
                    Delete delete = this.SDK.Delete(tag.Path, true);
                    if (delete != null)
                    {
                        if (delete.Msg == "ok")
                        {
                            SoundPlayer sound = new SoundPlayer("Windows Recycle.wav");
                            sound.Play();
                            foreach (ListViewItem lst in this.listView.Items)
                            {
                                if (lst.Text == tag.Name)
                                {
                                    lst.Remove();
                                    break;
                                }
                            }
                            if (string.IsNullOrEmpty(size))
                            {
                                foreach (TreeNode lst in this.treeView.SelectedNode.Nodes)
                                {
                                    if (((Tag)lst.Tag).Path == tag.Path)
                                    {
                                        this.treeView.Nodes.Remove(lst);
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show(delete.Msg, "删除错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show(this.SDK.ErrMsg, "删除错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else
            {
                MessageBox.Show("你没有选择要删除的文件", "删除错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        private void listView_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            if (this.isAddDirectory)
            {
                string afterName = e.Label;

                if (string.IsNullOrEmpty(afterName))
                {
                    MessageBox.Show("新建文件夹失败，文件夹名不能为空", "新建文件夹错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Tag tag = (Tag)this.listView.SelectedItems[0].Tag;
                    tag.Path = (tag.Path + "/" + afterName).Replace("//", "/");
                    Create create = this.SDK.Create(tag.Path);
                    if (create != null)
                    {
                        if (create.FileId.Length > 5)
                        {
                            this.isAddDirectory = false;
                            TreeNode node = this.treeView.SelectedNode.Nodes.Add("Folder_" + afterName, afterName, 1, 2);
                            node.Tag = new Tag(tag.Path);
                            this.treeView.SelectedNode.Expand();
                        }
                        else
                        {
                            MessageBox.Show(create.Msg, "新建文件夹错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show(this.SDK.ErrMsg, "新建文件夹错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            else if (isModeDirectory)
            {
                string afterName = e.Label;

                if (string.IsNullOrEmpty(afterName))
                {
                    MessageBox.Show("重命名失败，文件名不能为空", "重命名错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    Tag tag = (Tag)this.listView.SelectedItems[0].Tag;
                    Move mode = this.SDK.Move(tag.Path, tag.Path.Substring(0, tag.Path.LastIndexOf("/") + 1) + afterName);
                    if (mode != null)
                    {
                    }
                    else
                    {
                        this.listView.SelectedItems[0].Text = tag.Name;
                        MessageBox.Show(this.SDK.ErrMsg, "重命名错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            if (this.isAddDirectory)
            {
                this.listView.SelectedItems[0].Remove();
                this.isAddDirectory = false;
            }
            this.isModeDirectory = false;
            this.listView.LabelEdit = true;
        }

        private void tlsm_ListView_NewFolder_Click(object sender, EventArgs e)
        {
            TreeNode selectNode = this.treeView.SelectedNode;
            this.isAddDirectory = true;
            ListViewItem item = new ListViewItem();
            //  item.Text = file.Name;
            item.Tag = new Tag(this.lbl_Path.Text);

            item.SubItems.Add("");
            item.ImageIndex = 1;

            item.SubItems.Add(Icons.GetExtsDescription(string.Empty));
            item.SubItems.Add(DateTime.Now.ToString());

            this.listView.Items.Add(item);
            this.listView.LabelEdit = true;
            this.listView.Items[this.listView.Items.Count - 1].Selected = true;
            this.listView.SelectedItems[0].BeginEdit();
        }

        private void tlsm_ListView_ReName_Click(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1);
            if (isSelecte)
            {
                string size = this.listView.SelectedItems[0].SubItems[1].Text;
                string file = this.listView.SelectedItems[0].SubItems[0].Text;
                this.isModeDirectory = true;
                this.listView.LabelEdit = true;
                this.listView.SelectedItems[0].BeginEdit();
            }
        }

        private void tlsm_ListView_Copy_Click(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1);
            if (isSelecte)
            {
                this.CopyTag = (Tag)this.listView.SelectedItems[0].Tag;
                this.isCopyFiled = true;
                this.isCutFiled = false;
            }
        }

        private void tlsm_ListView_Cut_Click(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1);
            if (isSelecte)
            {
                this.CopyTag = (Tag)this.listView.SelectedItems[0].Tag;
                this.isCopyFiled = false;
                this.isCutFiled = true;
            }
        }

        private void tlsm_ListView_Paste_Click(object sender, EventArgs e)
        {
            if ((this.isCopyFiled || this.isCutFiled) && this.CopyTag != null)
            {
                if (this.CopyTag.Path == this.lbl_Path.Text + this.CopyTag.Name)
                {
                    MessageBox.Show("不能粘贴在相同目录", "操作错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                if (this.isCopyFiled)
                {
                    Copy copy = this.SDK.Copy(this.CopyTag.Path, this.lbl_Path.Text + this.CopyTag.Name);
                    if (copy != null)
                    {
                        this.LoadPath(this.lbl_Path.Text, this.treeView.SelectedNode, true);
                        this.isCopyFiled = false;
                    }
                    else
                    {
                        MessageBox.Show(this.SDK.ErrMsg, "复制文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else if (this.isCutFiled)
                {
                    Move move = this.SDK.Move(this.CopyTag.Path, this.lbl_Path.Text + this.CopyTag.Name);
                    if (move != null)
                    {
                        this.LoadPath(this.lbl_Path.Text, this.treeView.SelectedNode, true);
                        this.isCutFiled = false;
                    }
                    else
                    {
                        MessageBox.Show(this.SDK.ErrMsg, "剪切文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void tlsm_ListView_Down_Click(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1);
            if (isSelecte)
            {
                string url = this.SDK.Download(((Tag)this.listView.SelectedItems[0].Tag).Path);
                Process.Start(url);
            }
        }

        private void tlsm_ListView_Shares_Click(object sender, EventArgs e)
        {
            bool isSelecte = (this.listView.SelectedItems.Count == 1);
            if (isSelecte)
            {
                Shares shares = this.SDK.GetShares(((Tag)this.listView.SelectedItems[0].Tag).Path);
                if (shares != null)
                {
                    System.Diagnostics.Process.Start(shares.Url);
                }
                else
                {
                    MessageBox.Show(this.SDK.ErrMsg, "分享文件错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void tlsm_ListView_UPLoad_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = "c:\\";
            openFileDialog.Filter = "所有文件|*.*";
            openFileDialog.RestoreDirectory = true;
            openFileDialog.FilterIndex = 1;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string fName = openFileDialog.FileName;
                FileInfo fileOpen = new FileInfo(fName);
                FileStream file = fileOpen.Open(FileMode.Open);
                byte[] bb = new byte[file.Length];
                file.Read(bb, 0, (int)file.Length);
                file.Close();
                FileData filedata = this.SDK.UpLoadFile(this.lbl_Path.Text + fileOpen.Name, true, fileOpen.Name, bb);
                if (filedata != null)
                {
                    MessageBox.Show("文件已经上传成功", "上传文件成功", MessageBoxButtons.OK);
                    this.LoadPath(this.lbl_Path.Text, this.treeView.SelectedNode, true);
                }
                else
                {
                    MessageBox.Show(this.SDK.ErrMsg, "上传文件失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
    }
}
